package cn.blinkedu.qqlib;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.tencent.connect.UnionInfo;
import com.tencent.connect.UserInfo;
import com.tencent.connect.common.Constants;
import com.tencent.connect.share.QQShare;
import com.tencent.connect.share.QzoneShare;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.unity3d.player.UnityPlayer;

import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends UnityPlayerActivity {
    private final static String APP_ID = "101993349";    // 这里填你自己AppId
    private final static String TAG = "QQSdk";

    private Tencent mTencent = null;
    private IUiListener loginListener = null;           // 登录回调
    private IUiListener shareQQListener = null;         // QQ消息分享回调
    private IUiListener shareQZoneListener = null;      // QQ空间分享回调

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 初始化sdk
        mTencent = Tencent.createInstance(APP_ID, this.getApplicationContext());
        // 设置授权（很重要），如果没有设置授权，无法进行登录，会提示未授权
        if (Tencent.isPermissionNotGranted()) {
            Tencent.setIsPermissionGranted(true);
        }

        // 初始化登录回调
        loginListener = new BaseUiListener() {
            @Override
            public void onComplete(Object o) {
                JSONObject jsonObject = (JSONObject) o;
                // 保存openid和token
                initOpenIdAndToken(jsonObject);
                // 将接收到的json数据发到unity
                UnityPlayer.UnitySendMessage("QQSdk", "OnLoginComplete", jsonObject.toString());
            }
        };
        // 初始化分享到QQ回调
        shareQQListener = new BaseUiListener() {
            @Override
            public void onComplete(Object o) {
                Toast.makeText(MainActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }
        };
        // 初始化分享到QQ空间回调
        shareQZoneListener = new BaseUiListener() {
            @Override
            public void onComplete(Object o) {
                Toast.makeText(MainActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }
        };
    }

    // 登录QQ
    public void login() {
        // 判断会话是否有效，如果会话无效就进行登录操作
        if (!mTencent.isSessionValid()) {
            mTencent.login(this, "all", loginListener);
        }
    }

    // 注销登录
    public void logout() {
        if (mTencent != null) {
            mTencent.logout(this);
            UnityPlayer.UnitySendMessage("QQSdk", "OnLogout", "");
            Log.d(TAG, "logout! ");
        }
    }

    // 获取用户信息
    public void getUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            UserInfo info = new UserInfo(this, mTencent.getQQToken());
            info.getUserInfo(new BaseUiListener() {
                @Override
                public void onComplete(Object o) {
                    JSONObject jsonObject = (JSONObject) o;
                    UnityPlayer.UnitySendMessage("QQSdk", "OnGetUserInfoComplete", jsonObject.toString());
                }
            });
        }
    }

    // 获取UnionId
    public void getUnionId() {
        if (mTencent != null && mTencent.isSessionValid()) {
            UnionInfo unionInfo = new UnionInfo(this, mTencent.getQQToken());
            unionInfo.getUnionId(new BaseUiListener(){
                @Override
                public void onComplete(Object o) {
                    JSONObject jsonObject = (JSONObject) o;
                    UnityPlayer.UnitySendMessage("QQSdk", "OnGetUnionIdComplete", jsonObject.toString());
                }
            });
        }
    }

    // 分享到QQ
    public void shareToQQ(String title, String summary, String targetUrl, String imgUrl, String appName) {
        Bundle params = new Bundle();
        params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
        params.putString(QQShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QQShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
        params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, imgUrl);
        params.putString(QQShare.SHARE_TO_QQ_APP_NAME, appName);
        // 分享
        mTencent.shareToQQ(this, params, shareQZoneListener);
    }

    // 分享到QQ空间(图文)
    public void shareToQZone(String title, String summary, String targetUrl, String imgUrl, String appName) {
        Bundle params = new Bundle();
        params.putInt(QzoneShare.SHARE_TO_QZONE_KEY_TYPE, QzoneShare.SHARE_TO_QZONE_TYPE_IMAGE_TEXT);
        params.putString(QzoneShare.SHARE_TO_QQ_TITLE, title);
        params.putString(QzoneShare.SHARE_TO_QQ_SUMMARY, summary);
        params.putString(QzoneShare.SHARE_TO_QQ_TARGET_URL, targetUrl);
        ArrayList<String> arrayList = new ArrayList<>();
        arrayList.add(imgUrl);
        params.putStringArrayList(QzoneShare.SHARE_TO_QQ_IMAGE_URL, arrayList);
        params.putString(QzoneShare.SHARE_TO_QQ_APP_NAME, appName);
        // 分享
        mTencent.shareToQzone(this, params, shareQZoneListener);
    }


    // 保存token和openId
    private void initOpenIdAndToken(JSONObject o) {
        try {
            String token = o.getString(Constants.PARAM_ACCESS_TOKEN);
            String expires = o.getString(Constants.PARAM_EXPIRES_IN);
            String openId = o.getString(Constants.PARAM_OPEN_ID);
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires) && !TextUtils.isEmpty(openId)) {
                // 确保保存的数据不为空
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(openId);
                Log.d(TAG, "initOpenIdAndToken success!");
            } else {
                Log.e(TAG, "initOpenIdAndToken fail!");
            }
        } catch (Exception e) {
            Log.e(TAG, "initOpenIdAndToken: ", e);
        }
    }

    // 这个方法必须加，不然可能无法接收到回调
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IUiListener listener = null;
        if (requestCode == Constants.REQUEST_LOGIN || requestCode == Constants.REQUEST_APPBAR) {
            listener = loginListener;
        } else if (requestCode == Constants.REQUEST_QQ_SHARE) {
            listener = shareQQListener;
        } else if (requestCode == Constants.REQUEST_QZONE_SHARE) {
            listener = shareQZoneListener;
        }
        Tencent.onActivityResultData(requestCode, resultCode, data, listener);
        super.onActivityResult(requestCode, resultCode, data);
    }
}
